<script setup lang="ts">
import { reportApi } from "@/api/report-api";
import {
  resetPasswordApi,
  sendSmsCodeApi,
  smsLogin,
  verifyResetCodeApi
} from "@/api/user";
import globalization from "@/assets/svg/globalization.svg?component";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import { useLayout } from "@/layout/hooks/useLayout";
import { useNav } from "@/layout/hooks/useNav";
import { useTranslationLang } from "@/layout/hooks/useTranslationLang";
import { getTopMenu, initRouter } from "@/router/utils";
import { useToolsStore } from "@/store/modules/tools";
import { useUserStoreHook } from "@/store/modules/user";
import { setToken } from "@/utils/auth";
import { message } from "@/utils/message";
import { debounce } from "@pureadmin/utils";
import { useEventListener } from "@vueuse/core";
import type { FormInstance } from "element-plus";
import { nextTick, onMounted, onUnmounted, reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import countries from "world-countries";
import ArrowLeft from "~icons/ep/arrow-left";
import Check from "~icons/ep/check";
import Lock from "~icons/ri/lock-fill";
import User from "~icons/ri/user-3-fill";

defineOptions({
  name: "Login"
});

const router = useRouter();
const loading = ref(false);
const disabled = ref(false);
const ruleFormRef = ref<FormInstance>();
const phoneFormRef = ref<FormInstance>();

const { initStorage } = useLayout();
initStorage();

const { t } = useI18n();
const { dataTheme, overallStyle, dataThemeChange } = useDataThemeChange();
dataThemeChange(overallStyle.value);
const { title, getDropdownItemStyle, getDropdownItemClass } = useNav();
const { locale, translationCh, translationEn } = useTranslationLang();

// Tab切换
const activeTab = ref("sms");

// 页面状态管理
const currentView = ref("login"); // login, forgot-password, sms-verify, reset-password

// 短信验证码相关状态
const showSmsCodeInput = ref(false);
const isPhoneValid = ref(false);
const smsCodeDigits = ref(["", "", "", "", "", ""]);
const codeInputRefs = ref([]);
const resendDisabled = ref(false);
const countdown = ref(60);
let countdownTimer = null;

// 忘记密码相关状态
const forgotPasswordForm = reactive({
  phone: "",
  areaCode: "+86"
});

const resetPasswordForm = reactive({
  newPassword: "",
  confirmPassword: ""
});

const isForgotPhoneValid = ref(false);

// 用户协议
// const agreementChecked = ref(false);

// 密码登录表单
const ruleForm = reactive({
  username: "",
  password: ""
});

const loginRules = {
  username: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
  password: [{ required: true, message: "密码不能为空", trigger: "blur" }]
};

// 获取区号对应的国旗
const getCountryFlag = areaCode => {
  const option = areaCodeOptions.find(opt => opt.value === areaCode);
  return option ? option.flag : "🌍";
};

// 处理区号选项
const getAreaCodeOptions = () => {
  // 常用国家/地区的区号，按使用频率排序
  const commonCodes = [
    "+86",
    "+852",
    "+853",
    "+886",
    "+1",
    "+44",
    "+81",
    "+82",
    "+65",
    "+60",
    "+66",
    "+61"
  ];

  const countryMap = new Map();

  countries.forEach(country => {
    const callingCode = country.idd?.root + (country.idd?.suffixes?.[0] || "");
    if (callingCode && callingCode !== "undefined") {
      const flag = country.flag;
      const code = callingCode.startsWith("+")
        ? callingCode
        : `+${callingCode}`;

      // 只保留第一个遇到的国家（避免重复区号）
      if (!countryMap.has(code)) {
        countryMap.set(code, {
          value: code,
          flag: flag,
          name: country.name.common
        });
      }
    }
  });

  // 按常用程度排序
  const sortedOptions = [];

  // 先添加常用的
  commonCodes.forEach(code => {
    if (countryMap.has(code)) {
      sortedOptions.push(countryMap.get(code));
      countryMap.delete(code);
    }
  });

  // 再添加其他的，按区号数字排序
  const remaining = Array.from(countryMap.values()).sort((a, b) => {
    const numA = parseInt(a.value.replace("+", ""));
    const numB = parseInt(b.value.replace("+", ""));
    return numA - numB;
  });

  return [...sortedOptions, ...remaining];
};

const areaCodeOptions = getAreaCodeOptions();

// 短信登录表单
const smsForm = reactive({
  phone: "",
  smsCode: "",
  areaCode: "+86"
});

const phoneRules = {
  phone: [
    { required: true, message: "手机号不能为空", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback();
          return;
        }
        validatePhone();
        if (!isPhoneValid.value) {
          callback(new Error("请输入正确的手机号"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
};

// 设置验证码输入框引用
const setCodeInputRef = (el, index) => {
  if (el) {
    codeInputRefs.value[index] = el;
  }
};

// 验证手机号
const validatePhone = () => {
  const phoneRegex = /^1[3-9]\d{9}$/;
  isPhoneValid.value = phoneRegex.test(smsForm.phone);
};

// 验证忘记密码手机号
const validateForgotPhone = () => {
  const phoneRegex = /^1[3-9]\d{9}$/;
  isForgotPhoneValid.value = phoneRegex.test(forgotPasswordForm.phone);
};

// 格式化手机号显示
const formatPhone = phone => {
  if (!phone) return "";
  return phone.replace(/(\d{3})(\d{4})(\d{4})/, "$1****$3");
};

// 继续按钮点击
const onContinue = async () => {
  if (!isPhoneValid.value) return;

  // if (!agreementChecked.value) {
  //   message("请先阅读并同意用户协议和隐私政策", { type: "warning" });
  //   return;
  // }

  try {
    loading.value = true;
    await sendSmsCode();
    showSmsCodeInput.value = true;
    // 聚焦到第一个验证码输入框
    nextTick(() => {
      if (codeInputRefs.value[0]) {
        codeInputRefs.value[0].focus();
      }
    });
  } catch (e) {
    console.error(e);
    message("发送验证码失败", { type: "error" });
  } finally {
    loading.value = false;
  }
};

// 返回手机号输入
const goBack = () => {
  if (currentView.value === "sms-verify") {
    if (showSmsCodeInput.value) {
      currentView.value = "forgot-password";
    } else {
      currentView.value = "login";
    }
  } else if (currentView.value === "reset-password") {
    currentView.value = "sms-verify";
  } else {
    currentView.value = "login";
  }
  showSmsCodeInput.value = false;
  smsCodeDigits.value = ["", "", "", "", "", ""];
};

// 忘记密码
const onForgotPassword = () => {
  forgotPasswordForm.areaCode = "+86";
  currentView.value = "forgot-password";
};

// 发送重置密码验证码
const sendResetCode = async () => {
  if (!isForgotPhoneValid.value) return;

  try {
    loading.value = true;
    await sendSmsCodeApi({
      areaCode: forgotPasswordForm.areaCode,
      scene: "reset_password",
      phone: forgotPasswordForm.phone
    });
    message("验证码发送成功", { type: "success" });
    currentView.value = "sms-verify";
    startCountdown();
    // 聚焦到第一个验证码输入框
    nextTick(() => {
      if (codeInputRefs.value[0]) {
        codeInputRefs.value[0].focus();
      }
    });
  } catch (e) {
    console.error(e);
    message("发送验证码失败", { type: "error" });
  } finally {
    loading.value = false;
  }
};

// 验证重置密码验证码
const verifyResetCode = async () => {
  const code = smsCodeDigits.value.join("");
  if (code.length === 6) {
    try {
      loading.value = true;
      const result = await verifyResetCodeApi({
        phone: forgotPasswordForm.phone,
        areaCode: forgotPasswordForm.areaCode,
        smsCode: code,
        scene: "reset_password"
      });

      if (result.code === 0) {
        currentView.value = "reset-password";
        smsCodeDigits.value = ["", "", "", "", "", ""];
      } else {
        message("验证码错误", { type: "error" });
        smsCodeDigits.value = ["", "", "", "", "", ""];
        if (codeInputRefs.value[0]) {
          codeInputRefs.value[0].focus();
        }
      }
    } catch (e) {
      console.error(e);
      message("验证失败", { type: "error" });
      smsCodeDigits.value = ["", "", "", "", "", ""];
      if (codeInputRefs.value[0]) {
        codeInputRefs.value[0].focus();
      }
    } finally {
      loading.value = false;
    }
  }
};

// 重置密码
const onResetPassword = async () => {
  if (!resetPasswordForm.newPassword) {
    message("请输入新密码", { type: "error" });
    return;
  }

  if (!resetPasswordForm.confirmPassword) {
    message("请确认新密码", { type: "error" });
    return;
  }

  if (resetPasswordForm.newPassword !== resetPasswordForm.confirmPassword) {
    message("两次输入的密码不一致", { type: "error" });
    return;
  }

  if (resetPasswordForm.newPassword.length < 8) {
    message("密码长度不能少于8个字符", { type: "error" });
    return;
  }

  // 验证密码复杂度：至少包含数字、字母或符号中的两种
  const hasNumber = /\d/.test(resetPasswordForm.newPassword);
  const hasLetter = /[a-zA-Z]/.test(resetPasswordForm.newPassword);
  const hasSymbol = /[^a-zA-Z0-9]/.test(resetPasswordForm.newPassword);

  const typeCount = [hasNumber, hasLetter, hasSymbol].filter(Boolean).length;
  if (typeCount < 2) {
    message("密码需包含数字、字母或符号中的至少两种类型", { type: "error" });
    return;
  }

  try {
    loading.value = true;
    const result = await resetPasswordApi({
      phone: forgotPasswordForm.phone,
      areaCode: forgotPasswordForm.areaCode,
      newPassword: resetPasswordForm.newPassword
    });

    if (result.code === 0) {
      message("密码重置成功", { type: "success" });
      currentView.value = "login";
      resetPasswordForm.newPassword = "";
      resetPasswordForm.confirmPassword = "";
      // 清空忘记密码表单
      forgotPasswordForm.phone = "";
      forgotPasswordForm.areaCode = "+86";
    } else {
      message(result.message || "重置密码失败", { type: "error" });
    }
  } catch (e) {
    console.error(e);
    message("重置密码失败", { type: "error" });
  } finally {
    loading.value = false;
  }
};

// 验证码输入处理
const onCodeInput = (index, value) => {
  // Element Plus 的 @input 事件直接传递值，不是事件对象
  if (!/^\d*$/.test(value)) {
    smsCodeDigits.value[index] = "";
    return;
  }

  smsCodeDigits.value[index] = value;

  // 自动跳转到下一个输入框
  if (value && index < 5) {
    nextTick(() => {
      if (codeInputRefs.value[index + 1]) {
        codeInputRefs.value[index + 1].focus();
      }
    });
  }

  // 检查是否输入完成
  const code = smsCodeDigits.value.join("");
  if (code.length === 6) {
    if (currentView.value === "sms-verify") {
      // 重置密码验证码验证
      // verifyResetCode();
      currentView.value = "reset-password";
      smsCodeDigits.value = ["", "", "", "", "", ""];
    } else {
      // 登录验证码
      smsForm.smsCode = code;
      onSmsLogin();
    }
  }
};

// 验证码键盘事件处理
const onCodeKeydown = (index, event) => {
  if (event.key === "Backspace" && !smsCodeDigits.value[index] && index > 0) {
    nextTick(() => {
      if (codeInputRefs.value[index - 1]) {
        codeInputRefs.value[index - 1].focus();
      }
    });
  }
};

// 重新发送验证码
const resendCode = async () => {
  if (resendDisabled.value) return;

  try {
    loading.value = true;
    if (currentView.value === "sms-verify") {
      // 重置密码验证码
      await sendSmsCodeApi({
        areaCode: forgotPasswordForm.areaCode,
        scene: "reset_password",
        phone: forgotPasswordForm.phone
      });
    } else {
      // 登录验证码
      await sendSmsCode();
    }
    // startCountdown();
  } catch (e) {
    console.error(e);
    message("发送验证码失败", { type: "error" });
  } finally {
    loading.value = false;
  }
};

// 开始倒计时
const startCountdown = () => {
  resendDisabled.value = true;
  countdown.value = 60;
  countdownTimer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(countdownTimer);
      resendDisabled.value = false;
    }
  }, 1000);
};
// 初始化 store
const toolsStore = useToolsStore();
// 获取字典数据
const queryDictionaryData = async () => {
  try {
    const response = await reportApi.queryReportDict();
    if (response?.data) {
      toolsStore.setDictData(response.data);
      console.log("获取到的字典数据:", response.data);
    }
  } catch (err) {
    console.error("获取字典数据失败:", err);
    ElMessage.error("获取字典数据失败");
  }
};
// 密码登录
const onLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  // if (!agreementChecked.value) {
  //   message("请先阅读并同意用户协议和隐私政策", { type: "warning" });
  //   return;
  // }

  await formEl.validate(valid => {
    if (valid) {
      loading.value = true;
      useUserStoreHook()
        .loginByUsername({
          loginName: ruleForm.username,
          password: ruleForm.password
        })
        .then(res => {
          if (res.code == 0) {
            // 获取后端路由
            return initRouter().then(() => {
              disabled.value = true;
              router
                .push(getTopMenu(true).path)
                .then(() => {
                  queryDictionaryData();
                  message(t("login.pureLoginSuccess"), { type: "success" });
                })
                .finally(() => (disabled.value = false));
            });
          } else {
            message(res.message, { type: "error" });
          }
        })
        .finally(() => (loading.value = false));
    }
  });
};

// 短信登录
const onSmsLogin = async () => {
  try {
    loading.value = true;
    const loginRes = await smsLogin({
      phone: smsForm.phone,
      smsCode: smsForm.smsCode,
      areaCode: smsForm.areaCode
    });
    if (loginRes.code == 0) {
      setToken({
        accessToken: loginRes.data.token,
        expires: loginRes.data.expires
      });
      return initRouter().then(() => {
        disabled.value = true;
        router
          .push(getTopMenu(true).path)
          .then(() => {
            message("登录成功", { type: "success" });
          })
          .finally(() => (disabled.value = false));
      });
    } else {
      message(loginRes.message, { type: "error" });
    }
  } catch (e) {
    console.error(e);
    message("登录失败", { type: "error" });
    // 验证码错误时清空输入
    smsCodeDigits.value = ["", "", "", "", "", ""];
    if (codeInputRefs.value[0]) {
      codeInputRefs.value[0].focus();
    }
  } finally {
    loading.value = false;
  }
};

// 发送短信验证码
async function sendSmsCode() {
  await sendSmsCodeApi({
    areaCode: smsForm.areaCode,
    scene: "login",
    phone: smsForm.phone
  });
  message("验证码发送成功", { type: "success" });
  startCountdown();
}

const immediateDebounce: any = debounce(
  formRef => {
    if (activeTab.value === "sms") {
      if (!showSmsCodeInput.value) {
        onContinue();
      }
    } else {
      onLogin(formRef);
    }
  },
  1000,
  true
);

useEventListener(document, "keydown", ({ code }) => {
  if (
    ["Enter", "NumpadEnter"].includes(code) &&
    !disabled.value &&
    !loading.value
  )
    immediateDebounce(ruleFormRef.value);
});

onMounted(() => {
  // 初始化逻辑
});

onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
});
</script>

<template>
  <div class="select-none">
    <!-- 主题和国际化切换 -->
    <div class="flex-c absolute right-5 top-3 z-10">
      <!-- 国际化 -->
      <el-dropdown trigger="click">
        <globalization
          class="hover:text-primary hover:bg-[transparent]! w-[20px] h-[20px] ml-1.5 cursor-pointer outline-hidden duration-300"
        />
        <template #dropdown>
          <el-dropdown-menu class="translation">
            <el-dropdown-item
              :style="getDropdownItemStyle(locale, 'zh')"
              :class="['dark:text-white!', getDropdownItemClass(locale, 'zh')]"
              @click="translationCh"
            >
              <IconifyIconOffline
                v-show="locale === 'zh'"
                class="check-zh"
                :icon="Check"
              />
              简体中文
            </el-dropdown-item>
            <el-dropdown-item
              :style="getDropdownItemStyle(locale, 'en')"
              :class="['dark:text-white!', getDropdownItemClass(locale, 'en')]"
              @click="translationEn"
            >
              <span v-show="locale === 'en'" class="check-en">
                <IconifyIconOffline :icon="Check" />
              </span>
              English
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 登录容器 -->
    <div class="login-container">
      <!-- 左上角logo -->
      <div class="login-logo">
        <img
          src="@/assets/images/logo/login_logo.png"
          alt="Logo"
          class="logo-img"
        />
      </div>

      <!-- 正常登录状态 -->
      <div
        v-if="currentView === 'login' && !showSmsCodeInput"
        class="login-box"
      >
        <!-- 顶部图片和标题 -->
        <div class="login-header">
          <img
            class="login-top-img"
            src="@/assets/images/login/login_top.png"
          />
          <div class="system-title">
            <h2>海底捞</h2>
            <h3>健康管理系统</h3>
          </div>
        </div>

        <!-- Tab切换 -->
        <el-tabs v-model="activeTab" class="login-tabs">
          <el-tab-pane label="验证码登录" class="smsClass" name="sms">
            <el-form
              ref="phoneFormRef"
              class="login-form"
              :model="smsForm"
              :rules="phoneRules"
            >
              <el-form-item prop="phone">
                <el-input
                  v-model.trim="smsForm.phone"
                  placeholder="请输入体检时预约手机号"
                  class="phone-input"
                  @input="validatePhone"
                  @keyup.enter="onContinue"
                >
                  <template #prepend>
                    <el-select
                      v-model="smsForm.areaCode"
                      class="area-code-select"
                      placeholder="区号"
                      @change="validatePhone"
                    >
                      <template #prefix>
                        <span class="selected-flag">{{
                          getCountryFlag(smsForm.areaCode)
                        }}</span>
                      </template>
                      <el-option
                        v-for="option in areaCodeOptions"
                        :key="option.value"
                        :label="option.value"
                        :value="option.value"
                      >
                        <span class="area-code-option">
                          <span class="flag">{{ option.flag }}</span>
                          <span class="code">{{ option.value }}</span>
                        </span>
                      </el-option>
                    </el-select>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button
                  class="w-full btn"
                  type="primary"
                  :disabled="!isPhoneValid"
                  :loading="loading"
                  @click="onContinue"
                >
                  继续
                </el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>

          <el-tab-pane label="密码登录" name="password">
            <el-form
              ref="ruleFormRef"
              class="login-form"
              :model="ruleForm"
              :rules="loginRules"
            >
              <el-form-item prop="username">
                <el-input
                  v-model.trim="ruleForm.username"
                  placeholder="请输入用户名"
                  :prefix-icon="User"
                  @keyup.enter="onLogin(ruleFormRef)"
                />
              </el-form-item>
              <el-form-item prop="password">
                <el-input
                  v-model="ruleForm.password"
                  type="password"
                  placeholder="请输入密码"
                  :prefix-icon="Lock"
                  show-password
                  @keyup.enter="onLogin(ruleFormRef)"
                />
              </el-form-item>
              <el-form-item>
                <div class="forgot-password">
                  <a href="#" class="link" @click.prevent="onForgotPassword"
                    >忘记密码</a
                  >
                </div>
              </el-form-item>
              <el-form-item>
                <el-button
                  class="w-full btn"
                  type="primary"
                  :loading="loading"
                  :disabled="disabled"
                  @click="onLogin(ruleFormRef)"
                >
                  登录
                </el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>

        <!-- 用户协议和隐私政策 -->
        <!-- <div class="agreement-section-inner">
          <el-checkbox v-model="agreementChecked" class="agreement-checkbox">
            我已阅读并同意
            <a href="#" class="agreement-link">用户协议</a>
            和
            <a href="#" class="agreement-link">隐私政策</a>
            。
          </el-checkbox>
        </div> -->
      </div>

      <!-- 忘记密码页面 -->
      <div v-else-if="currentView === 'forgot-password'" class="reset-box">
        <div class="reset-step">
          <div class="back-btn" @click="goBack">
            <el-icon><ArrowLeft /></el-icon>
          </div>
          <h3 class="reset-title">重置密码</h3>
          <p class="reset-desc">
            请输入您的手机号码，我们将向您发送验证码以便重置密码。
          </p>
          <el-input
            v-model.trim="forgotPasswordForm.phone"
            placeholder="请输入体检时预约手机号"
            class="phone-input"
            @input="validateForgotPhone"
            @keyup.enter="sendResetCode"
          >
            <template #prepend>
              <el-select
                v-model="forgotPasswordForm.areaCode"
                class="area-code-select"
                placeholder="区号"
                @change="validateForgotPhone"
              >
                <template #prefix>
                  <span class="selected-flag">{{
                    getCountryFlag(forgotPasswordForm.areaCode)
                  }}</span>
                </template>
                <el-option
                  v-for="option in areaCodeOptions"
                  :key="option.value"
                  :label="option.value"
                  :value="option.value"
                >
                  <span class="area-code-option">
                    <span class="flag">{{ option.flag }}</span>
                    <span class="code">{{ option.value }}</span>
                  </span>
                </el-option>
              </el-select>
            </template>
          </el-input>

          <el-button
            class="w-full btn reset-btn"
            type="primary"
            :disabled="!isForgotPhoneValid"
            :loading="loading"
            @click="sendResetCode"
          >
            发送验证码
          </el-button>
        </div>
      </div>

      <!-- 验证码验证页面 -->
      <div v-else-if="currentView === 'sms-verify'" class="sms-code-box">
        <div class="sms-step">
          <div class="back-btn" @click="goBack">
            <el-icon><ArrowLeft /></el-icon>
          </div>
          <h3 class="sms-title">查看您的短信</h3>
          <p class="sms-desc">
            验证码已发送至电话号码 {{ forgotPasswordForm.areaCode }}
            {{ formatPhone(forgotPasswordForm.phone) }}
          </p>

          <div class="sms-code-input">
            <el-input
              v-for="(digit, index) in smsCodeDigits"
              :key="index"
              :ref="el => setCodeInputRef(el, index)"
              v-model="smsCodeDigits[index]"
              class="code-digit"
              :maxlength="1"
              @input="onCodeInput(index, $event)"
              @keydown="onCodeKeydown(index, $event)"
            />
          </div>

          <el-button
            class="w-full resend-section"
            type="primary"
            :disabled="resendDisabled"
            :loading="loading"
            @click="resendCode"
          >
            重新发送 {{ resendDisabled ? `(${countdown}s)` : "" }}
          </el-button>
        </div>
      </div>

      <!-- 设置新密码页面 -->
      <div
        v-else-if="currentView === 'reset-password'"
        class="reset-password-box"
      >
        <div class="reset-step">
          <div class="back-btn" @click="goBack">
            <el-icon><ArrowLeft /></el-icon>
          </div>
          <h3 class="reset-title">新密码</h3>
          <p class="reset-desc">
            密码仅可由数字、英文字母或英文符号组成，且需包含其中至少两种类型，长度不少于8个字符。
          </p>

          <div class="password-form">
            <el-input
              v-model="resetPasswordForm.newPassword"
              type="password"
              placeholder="输入新密码"
              class="password-input"
              show-password
            />
            <el-input
              v-model="resetPasswordForm.confirmPassword"
              type="password"
              placeholder="重复新密码"
              class="password-input"
              show-password
              @keyup.enter="onResetPassword"
            />
          </div>

          <el-button
            class="w-full btn reset-btn"
            type="primary"
            :loading="loading"
            @click="onResetPassword"
          >
            创建密码
          </el-button>

          <p class="reset-footer">重置密码后需返回登录页进行登录</p>
        </div>
      </div>

      <!-- 登录验证码输入状态 -->
      <div v-else-if="showSmsCodeInput" class="sms-code-box">
        <div class="sms-step">
          <div class="back-btn" @click="goBack">
            <el-icon><ArrowLeft /></el-icon>
          </div>
          <h3 class="sms-title">查看您的短信</h3>
          <p class="sms-desc">
            验证码已发送至电话号码 {{ smsForm.areaCode }}
            {{ formatPhone(smsForm.phone) }}
          </p>

          <div class="sms-code-input">
            <el-input
              v-for="(digit, index) in smsCodeDigits"
              :key="index"
              :ref="el => setCodeInputRef(el, index)"
              v-model="smsCodeDigits[index]"
              class="code-digit"
              :maxlength="1"
              @input="onCodeInput(index, $event)"
              @keydown="onCodeKeydown(index, $event)"
            />
          </div>

          <el-button
            class="w-full resend-section"
            type="primary"
            :disabled="resendDisabled"
            :loading="loading"
            @click="resendCode"
          >
            重新发送 {{ resendDisabled ? `(${countdown}s)` : "" }}
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 响应式设计 */
@media (width <= 480px) {
  .login-container {
    padding: 10px;
  }

  .login-box,
  .sms-code-box {
    width: 100%;
    max-width: 360px;
  }

  .login-tabs {
    padding: 15px 30px 30px;
  }

  .login-header {
    height: 160px;
  }

  .system-title h2 {
    font-size: 28px;
  }

  .system-title h3 {
    font-size: 16px;
  }

  .sms-code-box {
    padding: 30px 20px;
  }

  .sms-code-input {
    gap: 8px;
  }

  .code-digit {
    width: 40px;
    height: 48px;
    font-size: 18px;
  }

  .phone-input-group {
    flex-direction: column;
    gap: 12px;
  }

  .area-code-select {
    width: 100%;
  }

  .agreement-checkbox {
    font-size: 11px;
  }

  .agreement-checkbox ::v-deep(.el-checkbox__label) {
    font-size: 11px;
  }
}

.login-container {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100vh;
  padding: 20px;
  background: #f0f7fe;
}

.login-logo {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 10;
}

.logo-img {
  width: 120px;
  height: auto;
  max-height: 60px;
  object-fit: contain;
}

.login-box {
  position: relative;
  width: 420px;
  overflow: hidden;
  background: #fff;
  border-radius: 30px;
  box-shadow: 0 20px 40px rgb(0 0 0 / 10%);
}

.login-header {
  position: relative;
  height: 200px;
  padding: 40px;
}

.login-top-img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.system-title {
  position: relative;
  z-index: 2;
}

.system-title h2 {
  margin: 0 0 8px;
  font-size: 32px;
  font-weight: bold;
  color: #333;
}

.system-title h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  color: #666;
}

.login-tabs {
  padding: 20px 40px 40px;
}

.login-form .el-form-item {
  margin-bottom: 20px;
}

.login-form .el-form-item:last-child {
  margin-bottom: 0;
}

.login-form .el-input {
  height: 48px;
  border-radius: 8px;
}

.phone-input-group {
  display: flex;
  gap: 8px;
}

.area-code-select {
  width: 108px;
  flex-shrink: 0;
}
:deep .el-input-group__prepend .el-select {
  margin: 0 -24px;
}

.area-code-select .el-input {
  height: 48px;
  border-radius: 8px;
}

.area-code-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.area-code-option .flag {
  font-size: 16px;
  width: 20px;
  text-align: center;
}

.area-code-option .code {
  font-family: monospace;
  font-weight: 500;
}

.selected-flag {
  font-size: 16px;
  margin-right: 4px;
}

::v-deep .el-select__wrapper {
  min-height: 48px;
}

.phone-input {
  /* width: 210px; */
  flex: 1;
  background: #f8f9fa;
}

.forgot-password {
  margin-bottom: 10px;
  text-align: right;
}

.link {
  color: #1890ff;
  text-decoration: none;
}

.link:hover {
  color: #40a9ff;
  text-decoration: underline;
}

.btn {
  height: 44px;
  font-size: 16px;
  font-weight: 600;
  color: #fff;
  background: linear-gradient(180deg, #61e2ff 0%, #3ab5ff 100%);
  border: none;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.btn:hover {
  box-shadow: 0 8px 20px rgb(58 181 255 / 40%);
  transform: translateY(-2px);
}

.btn:active {
  transform: translateY(0);
}

.sms-code-box,
.reset-box,
.reset-password-box {
  position: relative;
  width: 420px;
  min-height: 506px;
  padding: 40px;
  overflow: hidden;
  background: #fff;
  border-radius: 20px;
  box-shadow: 0 20px 40px rgb(0 0 0 / 10%);
}

.sms-step {
  position: relative;
}

.back-btn {
  position: absolute;
  top: -20px;
  left: -20px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  cursor: pointer;
  border-radius: 50%;
  transition: background-color 0.3s;
}

.back-btn:hover {
  background-color: #f5f5f5;
}

.sms-title {
  margin: 20px 0 15px;
  font-size: 24px;
  font-weight: 600;
  color: #333;
  text-align: center;
}

.sms-desc {
  margin: 0 0 40px;
  font-size: 14px;
  line-height: 1.5;
  color: #666;
  text-align: center;
}

.sms-code-input {
  display: flex;
  gap: 12px;
  justify-content: center;
  margin-bottom: 40px;
}

.code-digit {
  width: 48px;
  height: 56px;
  font-size: 20px;
  font-weight: 600;
  text-align: center;
  border: 2px solid #e8e8e8;
  border-radius: 12px;
}

.code-digit:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgb(24 144 255 / 20%);
}

.resend-section {
  width: 100%;
  height: 44px;
  font-size: 14px;
  font-weight: 400;
  color: #fff;
  background: linear-gradient(180deg, #61e2ff 0%, #3ab5ff 100%);
  border-radius: 8px;
}

/* 重置密码相关样式 */
.reset-step {
  position: relative;
}

.reset-title {
  margin: 20px 0 15px;
  font-size: 24px;
  font-weight: 600;
  color: #333;
  text-align: center;
}

.reset-desc {
  margin: 0 0 40px;
  font-size: 14px;
  line-height: 1.5;
  color: #666;
  text-align: center;
}

.reset-btn {
  margin-top: 40px;
}

.reset-footer {
  margin: 20px 0 0;
  font-size: 12px;
  color: #999;
  text-align: center;
}

/* 新密码设置页面样式 */
.password-form {
  margin-bottom: 20px;
}

.password-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 48px;
  padding: 0 16px;
  margin-bottom: 20px;
  background: #f8f9fa;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
}

.password-label {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.password-icon {
  color: #999;
}

.password-input {
  margin-bottom: 20px;
  height: 50px;
}
:deep(.password-input .el-input__wrapper) {
  border-radius: 28px;
}

.password-input .el-input__inner {
  height: 48px;
  border-radius: 8px;
}

/* 用户协议样式 */
.agreement-section-inner {
  padding-bottom: 20px;
}

.agreement-checkbox {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #666;
  line-height: 1.4;
}

.agreement-checkbox ::v-deep(.el-checkbox__label) {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
}

.agreement-link {
  color: #1890ff;
  text-decoration: none;
  margin: 0 2px;
}

.agreement-link:hover {
  color: #40a9ff;
  text-decoration: underline;
}

.translation {
  ::v-deep(.el-dropdown-menu__item) {
    padding: 5px 40px;
  }

  .check-zh {
    position: absolute;
    left: 20px;
  }

  .check-en {
    position: absolute;
    left: 20px;
  }
}
</style>
<style>
.smsClass .el-form-item__error {
  padding-left: 100px;
}
</style>
